package com.onlinelibrary.activities.star;
import android.annotation.SuppressLint;
import android.app.Application;
import android.view.View;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.databinding.BindingAdapter;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.MutableLiveData;
import com.onlinelibrary.R;
import com.onlinelibrary.utils.Http;
import com.onlinelibrary.view.FallObject;
import com.onlinelibrary.view.FallingView;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class StarVM extends AndroidViewModel {
    public static MutableLiveData<Float> rating=new MutableLiveData<>();
    @SuppressLint("StaticFieldLeak")
    private static StarActivity starActivity;
    public StarVM(@NonNull Application application) {
        super(application);
        rating.setValue(3f);
    }
    public void setBinding(StarActivity starActivity) {
        StarVM.starActivity = starActivity;
    }
    public static void submit(View view){
        try {
            JSONObject jo=new JSONObject();
            jo.put("type","new_star");
            jo.put("num",rating.getValue());
            Http.post(jo, "star/", new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) { }
                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) {
                    starActivity.runOnUiThread(() -> {
                        Toast.makeText(starActivity, "感谢您的评分！", Toast.LENGTH_SHORT).show();
                        starActivity.finish();
                    });
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    @BindingAdapter("bindFall")
    public static void bindFall(FallingView fallingView, StarVM starVM){
        @SuppressLint("UseCompatLoadingForDrawables") FallObject.Builder builder = new FallObject.Builder(starActivity.getResources().getDrawable(R.drawable.lib));
        FallObject fallObject = builder.setSpeed(7, true).setSize(150, 150, true).setWind(true, false).build();
        fallingView.addFallObject(fallObject, 15);
        fallingView.bringToFront();
    }
}